package com.primeton.poctag.task;

import org.apache.commons.exec.ProcessDestroyer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * <pre>
 *
 * Created by zhaopx.
 * User: zhaopx
 * Date: 2019/6/3
 * Time: 18:40
 *
 * </pre>
 *
 * @author zhaopx
 */
public class PidProcessDestroyer implements ProcessDestroyer {
    public static final String PID = "pid";


    private static Logger logger = LoggerFactory.getLogger(PidProcessDestroyer.class);


    final String taskId;




    /**
     * 进程 ID， 如果没有获取到取值 -1
     */
    private int processId = -1;


    /**
     * 根据 TaskId 更新 Task 状态
     * @param taskId
     */
    public PidProcessDestroyer(String taskId) {
        this.taskId = taskId;
    }


    /**
     * 获取子进程内 Process PID
     *
     * @param process
     * @return
     */
    public static int getProcessId(Process process) {
        int processId = 0;
        try {
            Field f = process.getClass().getDeclaredField(PID);
            f.setAccessible(true);
            processId = f.getInt(process);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }
        return processId;
    }

    @Override
    public boolean add(Process process) {
        processId = getProcessId(process);
        logger.info("task {} state RUNNING pid {}", taskId, processId);
        //taskHistService.updateTaskPid(taskId, "RUNNING", processId);
        return true;
    }

    @Override
    public boolean remove(Process process) {
        return true;
    }

    @Override
    public int size() {
        return 1;
    }


    public int getPid() {
        return processId;
    }
}
